package com.example.selfcontrol.utils;

import com.alibaba.fastjson2.JSON;
import com.example.selfcontrol.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletResponse;
import java.util.Date;

public class JwtUtils {
    private static final String SECRET_KEY = "ddadlamdasjdpawjdpajdpamiknoiafhoiafpafjkankfjansflanflanflafnlafnskla";
    // 密钥不能太短，并且符合base64编码
    private static final long EXPIRATION_TIME = 86400000; // 24 hours

    // 生成JwtToken
    public static String generateToken(User user) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION_TIME);
        Claims claims = Jwts.claims().setSubject("user") ;
        claims.put("data",user);

        return Jwts.builder()
                .setIssuedAt(now)
                .setExpiration(expiration)
                .setClaims(claims)      // payload一定需要一个claims否则生成签名报错
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 判断JwtToken是否有效
    public static boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            System.out.println(claims);
            return true ;
        } catch (Exception e) {
            return false ;
        }
    }

    // 解析JwtToken
    public static Object decodeJwtToken(String token) {
        Jws<Claims> claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
        Claims body = claims.getBody() ;
        Object user = body.get("data") ;
        System.out.println(user);

        return user ;
    }

    // 判断要更新User的token和他自己的更新信息是否匹配
    public static boolean isUserRight(String token, User user) {
        Object obj = decodeJwtToken(token);
        User user_obj = JSON.parseObject(JSON.toJSONString(obj),User.class) ;


        System.out.println(user_obj.getId());
        System.out.println(user.getId());

        if(user_obj.getId().equals(user.getId()))   return true ;
        return false ;
    }

    public static String getJWTTokenFromHeader(HttpServletRequest httpRequest) {
        String authorizationHeader = httpRequest.getHeader("Authorization");

        if(authorizationHeader == null) return null;
        String jwtToken = authorizationHeader.substring(7) ; // 去除bearer前缀
        return jwtToken ;
    }
}